package com.cff.action;

import java.awt.Color;
import java.awt.HeadlessException;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.text.JTextComponent;

import org.apache.commons.lang3.StringUtils;

import com.cff.common.Constant;
import com.cff.common.SimpleFrame;
import com.cff.util.EventUtil;
import com.cff.util.FileUtil;
import com.cff.util.RSAUtil;
import com.cff.util.SignTools;

public class BoxVerifyActionListener implements ActionListener {

	private String KeyType;
	private JFrame tmpFrame;
	private JTextArea dataText;
	private JTextArea keyText;
	public final static String FILEPATH = "D:/Document/Importance/";
	public static String tmpKey="";
	public BoxVerifyActionListener(String KeyType, JFrame tmpFrame, JTextArea dataText, JTextArea keyText) {
		super();
		this.KeyType = KeyType;
		this.tmpFrame = tmpFrame;
		this.dataText = dataText;
		this.keyText = keyText;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (Constant.BOXVERIFY.equals(KeyType)) {
			String userIn = dataText.getText().trim();
			String passwdIn = keyText.getText().trim();
			if (StringUtils.isEmpty(userIn) || StringUtils.isEmpty(passwdIn)) {
				JOptionPane.showMessageDialog(null, "用户名或密码错误！");
				return;
			}
			String path = FILEPATH + "access.fei";
			File file = new File(path);
			if (!file.exists()) {
				tmpFrame.dispose();
				JOptionPane.showMessageDialog(null, "无授权文件！");
				return;
			}
			InputStreamReader read = null;
			try {
				read = new InputStreamReader(new FileInputStream(file), "gbk");
			} catch (UnsupportedEncodingException e2) {
				e2.printStackTrace();
			} catch (FileNotFoundException e2) {
				e2.printStackTrace();
			}
			BufferedReader br = new BufferedReader(read);
			String line = "";
			String user = "";
			String passwd = "";
			String pubkey = "";
			String prikey = "";
			String bitmap = "";
			List<String> content = new ArrayList<String>();
			try {
				while ((line = br.readLine()) != null) {
					content.add(line);
				}
				if (content.size() < 5) {
					JOptionPane.showMessageDialog(null, "授权文件不完整！");
					return;
				}
				pubkey = content.get(0).trim();
				prikey = content.get(1).trim();
				user = content.get(2).trim();
				passwd = content.get(3).trim();
				bitmap = content.get(4).trim();
				int pos = Integer.parseInt(user.substring(user.length() - 4, user.length() - 2));
				int len = Integer.parseInt(user.substring(user.length() - 2, user.length()));
				passwd = passwd.substring(0, pos) + passwd.substring(pos + len, passwd.length());
				// bitmap = bitmap.substring(0, pos) +
				// bitmap.substring(pos+len,bitmap.length());
				System.out.println(passwd);
				if (!(user.equals(userIn) && (RSAUtil.decrypt(passwd, prikey)).equals(passwdIn))) {
					tmpFrame.dispose();
					JOptionPane.showMessageDialog(null, "用户名或密码错误！");
					return;
				}

				File rsaFile = new File(FILEPATH + "passwd.fei");
				if (!rsaFile.exists()) {
					tmpFrame.dispose();
					JOptionPane.showMessageDialog(null, "无密码文件！");
					return;
				}
				tmpFrame.dispose();
				showFileContent(FILEPATH + "passwd.fei", prikey, pubkey, pos, len);
			} catch (IOException e1) {
				e1.printStackTrace();
			} catch (HeadlessException e1) {
				e1.printStackTrace();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}

	}

	public void showFileContent(String fileName, String priKey, final String pubKey, final int pos, final int len)
			throws Exception {
		// 读文件并存入map
		final Map<String, ArrayList> msgBuffer = new HashMap<String, ArrayList>();
		final Map<String,Integer> pointPos = new HashMap<String,Integer>();

//		InputStreamReader read = null;
//		try {
//			read = new InputStreamReader(new FileInputStream(file), "gbk");
//		} catch (UnsupportedEncodingException e2) {
//			e2.printStackTrace();
//		} catch (FileNotFoundException e2) {
//			e2.printStackTrace();
//		}
		
		final RandomAccessFile access = new RandomAccessFile(fileName, "rw");
//		BufferedReader br = new BufferedReader(read);
		String passwdStr = "";
		int pointLen = 0;
		try {
			while ((passwdStr = access.readLine()) != null) {
				System.out.println(passwdStr);
				int pointTmpLen = passwdStr.length() + 2;
				passwdStr = passwdStr.substring(0, pos) + passwdStr.substring(pos + len, passwdStr.length());
				String passwd = RSAUtil.decrypt(passwdStr, priKey);
				String passArray[] = passwd.split("\\|");
				if (passArray.length != 3) {
					continue;
				}
				
				ArrayList<String> userPass = new ArrayList<String>();
				userPass.add(passArray[1]);
				userPass.add(passArray[2]);
				msgBuffer.put(passArray[0], userPass);
				pointPos.put(passArray[0], pointLen);
				pointLen += pointTmpLen;
			}
			access.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
//		try {
//			br.close();
//			read.close();
//		} catch (IOException e1) {
//			e1.printStackTrace();
//		}

		System.out.println(msgBuffer.toString());
		// 添加显示窗口
		JFrame tmpFrame = new JFrame();
		tmpFrame.setBounds(200, 50, 800, 660);
		tmpFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		tmpFrame.setLayout(null);
		final JComboBox msgAll = new JComboBox();
		final TextArea textMsg = new TextArea();
		msgAll.setBounds(10, 10, 200, 30);
		textMsg.setBounds(300, 10, 400, 300);
		JButton okButton = new JButton("新增");
		okButton.setBounds(50, 100, 100, 50);
		JButton editButton = new JButton("修改");
		editButton.setBounds(50, 200, 100, 50);
		msgAll.setEditable(true);
		Set msgKeySet = msgBuffer.keySet();
		Iterator i = msgKeySet.iterator();
		msgAll.addItem("请选择");
		while (i.hasNext()) {
			msgAll.addItem(i.next());
		}
		msgAll.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				int index = msgAll.getSelectedIndex();
				if (index != 0) { // ==0表示选中的事第一个
					String content = msgAll.getSelectedItem().toString();
					tmpKey = content;
					textMsg.setText("");
					for (int i = 0; i < msgBuffer.get(content).size(); i++) {
						textMsg.append(msgBuffer.get(content).get(i).toString());
						textMsg.append("\n");
					}

				}

			}
		});
		okButton.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				final JFrame tmpFrame = new JFrame();
				tmpFrame.setBounds(200, 200, 600, 350);
				tmpFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
				tmpFrame.setLayout(null);

				JLabel dataLabel = new JLabel();
				dataLabel.setBounds(20, 35, 100, 40);
				dataLabel.setText("用户名：");

				final JTextArea dataText = new JTextArea();
				dataText.setBounds(130, 35, 350, 40);
				dataText.setSelectedTextColor(Color.RED);
				dataText.setLineWrap(true); // 激活自动换行功能
				dataText.setWrapStyleWord(true); // 激活断行不断字功能
				JLabel keyLabel = new JLabel();
				keyLabel.setBounds(20, 95, 100, 40);
				keyLabel.setText("密码：");

				final JTextArea keyText = new JTextArea();
				keyText.setBounds(130, 95, 350, 40);
				keyText.setText("");
				keyText.setSelectedTextColor(Color.RED);
				keyText.setLineWrap(true); // 激活自动换行功能
				keyText.setWrapStyleWord(true); // 激活断行不断字功能

				JLabel descLabel = new JLabel();
				descLabel.setBounds(20, 155, 100, 40);
				descLabel.setText("描述：");

				final JTextArea descText = new JTextArea();
				descText.setBounds(130, 155, 350, 40);
				descText.setText("");
				descText.setSelectedTextColor(Color.RED);
				descText.setLineWrap(true); // 激活自动换行功能
				descText.setWrapStyleWord(true); // 激活断行不断字功能

				JButton okButton = new JButton("确定");
				okButton.setBounds(tmpFrame.getWidth() / 2 - 50, tmpFrame.getHeight() - 80, 70, 30);

				tmpFrame.add(dataLabel);
				tmpFrame.add(dataText);
				tmpFrame.add(keyLabel);
				tmpFrame.add(keyText);
				tmpFrame.add(descLabel);
				tmpFrame.add(descText);
				tmpFrame.add(okButton);
				okButton.addActionListener(new ActionListener() {
					public void actionPerformed(final ActionEvent e) {
						tmpFrame.dispose();
						String fileName = FILEPATH + "passwd.fei";
						File rsaFile = new File(FILEPATH + "passwd.fei");
						if (!rsaFile.exists()) {
							try {
								rsaFile.createNewFile();
							} catch (IOException e1) {
								e1.printStackTrace();
							}
						}
						String content = "";
						String userName = dataText.getText().trim();
						String passwd = keyText.getText().trim();
						String desc = descText.getText().trim();
						content = desc + "|" + userName + "|" + passwd;
						System.out.println(content);
						try {
							content = RSAUtil.encrypt(content, pubKey);
						} catch (Exception e2) {
							e2.printStackTrace();
						}
						if (passwd.length() < 20) {

							if (passwd.length() == 19) {
								passwd = passwd + "=";
							} else {
								String KeyString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
								int len = KeyString.length();
								int length = 20 - passwd.length();
								for (int j = 0; j < length; j++) {
									if (j == (length - 1) || j == 0)
										passwd = passwd + "=";
									else {
										passwd += KeyString.charAt((int) Math.round(Math.random() * (len - 1)));
									}
								}
							}
						} else if (passwd.length() > 20) {
							passwd = passwd.substring(0, 20);
						}
						System.out.println(passwd);
						System.out.println(content);
						content = content.substring(0, pos) + passwd + content.substring(pos, content.length());
						try {
							FileWriter writer = new FileWriter(fileName, true);
							BufferedWriter buffer = new BufferedWriter(writer);
							buffer.write(content);
							buffer.newLine();
							buffer.flush();
							writer.flush();
							buffer.close();
							writer.close();
							writer.close();

						} catch (IOException e1) {
							e1.printStackTrace();
						}

					}
				});
				tmpFrame.setVisible(true);
			}
		});

		editButton.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				final JFrame tmpFrame = new JFrame();
				tmpFrame.setBounds(200, 200, 600, 350);
				tmpFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
				tmpFrame.setLayout(null);

				JLabel dataLabel = new JLabel();
				dataLabel.setBounds(20, 35, 100, 40);
				dataLabel.setText("用户名：");

				final JTextArea dataText = new JTextArea();
				dataText.setBounds(130, 35, 350, 40);
				dataText.setSelectedTextColor(Color.RED);
				dataText.setLineWrap(true); // 激活自动换行功能
				dataText.setWrapStyleWord(true); // 激活断行不断字功能
				dataText.setText(msgBuffer.get(tmpKey).get(0).toString());
				
				JLabel keyLabel = new JLabel();
				keyLabel.setBounds(20, 95, 100, 40);
				keyLabel.setText("密码：");

				final JTextArea keyText = new JTextArea();
				keyText.setBounds(130, 95, 350, 40);
				keyText.setText("");
				keyText.setSelectedTextColor(Color.RED);
				keyText.setLineWrap(true); // 激活自动换行功能
				keyText.setWrapStyleWord(true); // 激活断行不断字功能
				keyText.setText(msgBuffer.get(tmpKey).get(1).toString());
				
				JLabel descLabel = new JLabel();
				descLabel.setBounds(20, 155, 100, 40);
				descLabel.setText("描述：");

				final JTextArea descText = new JTextArea();
				descText.setBounds(130, 155, 350, 40);
				descText.setText("");
				descText.setSelectedTextColor(Color.RED);
				descText.setLineWrap(true); // 激活自动换行功能
				descText.setWrapStyleWord(true); // 激活断行不断字功能
				descText.setText(tmpKey);

				JButton okButton = new JButton("确定");
				okButton.setBounds(tmpFrame.getWidth() / 2 - 50, tmpFrame.getHeight() - 80, 70, 30);

				tmpFrame.add(dataLabel);
				tmpFrame.add(dataText);
				tmpFrame.add(keyLabel);
				tmpFrame.add(keyText);
				tmpFrame.add(descLabel);
				tmpFrame.add(descText);
				tmpFrame.add(okButton);
				okButton.addActionListener(new ActionListener() {
					public void actionPerformed(final ActionEvent e) {
						tmpFrame.dispose();
						String fileName = FILEPATH + "passwd.fei";
						RandomAccessFile access = null;

						try {
							access = new RandomAccessFile(fileName, "rw");
						} catch (FileNotFoundException e3) {
							e3.printStackTrace();
						} // “读写”方式建立类的实例
						
						String content = "";
						String userName = dataText.getText().trim();
						String passwd = keyText.getText().trim();
						String desc = descText.getText().trim();
						content = desc + "|" + userName + "|" + passwd;
						System.out.println(content);
						try {
							content = RSAUtil.encrypt(content, pubKey);
						} catch (Exception e2) {
							e2.printStackTrace();
						}
						if (passwd.length() < 20) {

							if (passwd.length() == 19) {
								passwd = passwd + "=";
							} else {
								String KeyString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
								int len = KeyString.length();
								int length = 20 - passwd.length();
								for (int j = 0; j < length; j++) {
									if (j == (length - 1) || j == 0)
										passwd = passwd + "=";
									else {
										passwd += KeyString.charAt((int) Math.round(Math.random() * (len - 1)));
									}
								}
							}
						} else if (passwd.length() > 20) {
							passwd = passwd.substring(0, 20);
						}
						System.out.println(passwd);
						System.out.println(content);
						content = content.substring(0, pos) + passwd + content.substring(pos, content.length());
						try {
							access.seek(pointPos.get(tmpKey));
							access.writeBytes(content);
							access.writeBytes("\r\n");
							access.close();
						} catch (IOException e1) {
							e1.printStackTrace();
						}

					}
				});
				tmpFrame.setVisible(true);
			}
		});

		tmpFrame.add(msgAll);
		tmpFrame.add(textMsg);
		tmpFrame.add(okButton);
		tmpFrame.add(editButton);
		tmpFrame.setVisible(true);
	}

	public static void main(String args[]) throws IOException {
		String fileName = FILEPATH + "passwd.fei";
		RandomAccessFile access = new RandomAccessFile(fileName, "rw"); // “读写”方式建立类的实例
		String content = access.readLine();
		System.out.println(content);
		System.out.println(content.length());
		System.out.println("RandomAccessFile文件指针的初始位置:"+access.getFilePointer());  
		access.seek(content.length()*2+4);//移动文件指针位置 
		System.out.println(access.readLine());
		System.out.println("RandomAccessFile文件指针的初始位置:"+access.getFilePointer()); 
		access.seek(content.length()*2+4);//移动文件指针位置 
		access.writeBytes(content);
		access.writeBytes("\r\n");
	}

}
